<template>
  <div class="ad-container">
    <!-- 搜索栏 -->
    <el-form :inline="true" :model="searchForm" class="ad-search-bar">
      <el-form-item label="广告名称">
        <el-input v-model="searchForm.name" placeholder="请输入内容" clearable style="width: 220px;" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
        <el-button type="danger" plain @click="handleCreate">新建广告</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格 -->
    <el-table :data="pagedAds" style="width: 100%; margin-top: 18px;" border @row-click="handleRowClick">
      <el-table-column prop="name" label="广告名称" min-width="160" />
      <el-table-column label="图片" min-width="100">
        <template #default="scope">
          <el-image :src="scope.row.img" style="width:48px;height:48px;" fit="cover" v-if="scope.row.img" />
          <div v-else class="ad-img-placeholder"><el-icon><Picture /></el-icon></div>
        </template>
      </el-table-column>
      <el-table-column prop="position" label="广告位值" min-width="120" />
      <el-table-column prop="time" label="时间" min-width="220" />
      <el-table-column prop="clicks" label="点击次数" min-width="100" />
      <el-table-column prop="status" label="状态" min-width="80">
        <template #default="scope">
          <span v-if="scope.row.status === '上线'" style="color:#409eff;">上线</span>
          <span v-else style="color:#aaa;">下线</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="140">
        <template #default="scope">
          <el-button type="primary" link size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="primary" link size="small" @click="handleOffline(scope.$index, scope.row)">下线</el-button>
          <el-button type="danger" link size="small" style="color:#f56c6c;" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="ad-pagination">
      <el-pagination
        background
        layout="sizes, prev, pager, next, total"
        :total="adList.length"
        :page-size="pageSize"
        :current-page="currentPage"
        :page-sizes="pageSizes"
        @current-change="handlePageChange"
        @size-change="val => { pageSize = val; currentPage = 1; }"
        style="margin-top: 18px;"
      />
      <span class="ad-total">当前条件共检索到 <span style="color:#f56c6c;">{{ adList.length }}</span> 条相关信息</span>
    </div>

    <el-dialog v-model="showDialog" :title="isEdit ? '编辑广告' : '新建广告'" width="480px" :close-on-click-modal="false">
      <el-form :model="newAdForm" :rules="formRules" ref="adFormRef" label-width="90px" label-position="left">
        <el-form-item label="广告名称" prop="name" required>
          <el-input v-model="newAdForm.name" placeholder="请输入广告名称" />
        </el-form-item>
        <el-form-item label="广告位置" prop="position" required>
          <el-select v-model="newAdForm.position" placeholder="请选择所属分类">
            <el-option v-for="item in positionOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="order" required>
          <el-input v-model="newAdForm.order" placeholder="请输入排序号" type="number" />
        </el-form-item>
        <el-form-item label="状态" prop="status" required>
          <el-button-group>
            <el-button :type="newAdForm.status==='上线'?'primary':''" @click="newAdForm.status='上线'">上线</el-button>
            <el-button :type="newAdForm.status==='下线'?'danger':''" @click="newAdForm.status='下线'" style="color:#f56c6c;">下线</el-button>
          </el-button-group>
        </el-form-item>
        <el-form-item label="广告图片" prop="img" required>
          <el-upload
            class="ad-upload"
            action=""
            :show-file-list="false"
            :before-upload="beforeImgUpload"
            :on-change="handleImgChange"
          >
            <div class="ad-upload-box">
              <img v-if="newAdForm.img" :src="newAdForm.img" style="width:100px;height:50px;object-fit:cover;" />
              <div v-else class="ad-upload-placeholder">+</div>
            </div>
          </el-upload>
          <div style="margin-left:12px;color:#888;font-size:13px;">
            750*380像素<br/>仅支持JPG / PNG格式
          </div>
        </el-form-item>
        <el-form-item label="跳转类型" prop="jumpType" required>
          <el-select v-model="newAdForm.jumpType" placeholder="请选择跳转类型">
            <el-option v-for="item in jumpTypeOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showDialog=false">取消</el-button>
        <el-button type="primary" @click="submitAd">确定</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="showOfflineDialog" title="提示" width="400px" :close-on-click-modal="false">
      <div style="font-size:16px;">
        确定要下线 <span style="color:#f56c6c;">{{ offlineName }}</span> 吗?
      </div>
      <template #footer>
        <el-button @click="showOfflineDialog=false">取消</el-button>
        <el-button type="danger" @click="confirmOffline">确定</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="showDeleteDialog" title="提示" width="400px" :close-on-click-modal="false">
      <div style="font-size:16px;">
        确定要删除 <span style="color:#f56c6c;">{{ deleteName }}</span> 吗?
      </div>
      <template #footer>
        <el-button @click="showDeleteDialog=false">取消</el-button>
        <el-button type="danger" @click="confirmDelete">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, reactive, nextTick } from 'vue';
import { Picture } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

const searchForm = ref({ name: '' });

const showDialog = ref(false);
const adFormRef = ref();
const positionOptions = ['首页轮播图', '分类Banner', '活动Banner'];
const jumpTypeOptions = ['无跳转', '商品页', '活动页'];

const newAdForm = reactive({
  name: '',
  position: '',
  order: '',
  status: '下线',
  img: '',
  jumpType: ''
});
const formRules = {
  name: [{ required: true, message: '请输入广告名称', trigger: 'blur' }],
  position: [{ required: true, message: '请选择广告位置', trigger: 'change' }],
  order: [{ required: true, message: '请输入排序号', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
  img: [{ required: true, message: '请上传广告图片', trigger: 'change' }],
  jumpType: [{ required: true, message: '请选择跳转类型', trigger: 'change' }]
};

const isEdit = ref(false);
let editIndex = -1;

function handleEdit(index: number, row: any) {
  isEdit.value = true;
  editIndex = index;
  showDialog.value = true;
  nextTick(() => {
    if (adFormRef.value) adFormRef.value.clearValidate();
    Object.assign(newAdForm, row);
  });
}

function handleCreate() {
  isEdit.value = false;
  showDialog.value = true;
  nextTick(() => {
    if (adFormRef.value) adFormRef.value.resetFields();
    Object.assign(newAdForm, { name: '', position: '', order: '', status: '下线', img: '', jumpType: '' });
  });
}

function beforeImgUpload(file: File) {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  const isRightSize = true; // 可加尺寸校验
  if (!isJpgOrPng) {
    ElMessage.error('仅支持JPG/PNG格式');
    return false;
  }
  // 可加尺寸校验
  return true;
}
function handleImgChange(file: any) {
  const reader = new FileReader();
  reader.onload = e => {
    newAdForm.img = e.target?.result as string;
  };
  reader.readAsDataURL(file.raw);
}

function submitAd() {
  adFormRef.value.validate((valid: boolean) => {
    if (!valid) return;
    if (isEdit.value && editIndex > -1) {
      // 编辑模式，更新对应项
      adList.value[editIndex] = { ...newAdForm };
    } else {
      // 新建模式
      adList.value.unshift({
        name: newAdForm.name,
        img: newAdForm.img,
        position: newAdForm.position,
        time: new Date().toLocaleString(),
        clicks: 0,
        status: newAdForm.status,
        order: newAdForm.order,
        jumpType: newAdForm.jumpType
      });
    }
    localStorage.setItem('adList', JSON.stringify(adList.value));
    showDialog.value = false;
  });
}

// 初始化广告数据，优先从localStorage读取
const allAds = JSON.parse(localStorage.getItem('adList') || 'null') || [
  { name: '夏季大热促销', img: '', position: '首页轮播图', time: '2021-03-02 15:47:44~2017-03-12 15:47:44', clicks: 231, status: '上线' },
  { name: '新品发布会', img: '', position: '首页轮播图', time: '2021-03-02 15:47:44~2017-03-12 15:47:44', clicks: 324, status: '上线' },
  { name: '限时秒杀', img: '', position: '首页轮播图', time: '2021-03-02 15:47:44~2017-03-12 15:47:44', clicks: 1234, status: '上线' },
  { name: '会员专享福利', img: '', position: '首页轮播图', time: '2021-03-02 15:47:44~2017-03-12 15:47:44', clicks: 322, status: '上线' },
  { name: '年终盛典', img: '', position: '首页轮播图', time: '2021-03-02 15:47:44~2017-03-12 15:47:44', clicks: 888, status: '上线' },
  { name: '品牌日', img: '', position: '首页轮播图', time: '2021-03-02 15:47:44~2017-03-12 15:47:44', clicks: 666, status: '上线' },
  { name: '清仓特卖', img: '', position: '首页轮播图', time: '2021-03-02 15:47:44~2017-03-12 15:47:44', clicks: 555, status: '上线' },
  { name: '节日专场', img: '', position: '首页轮播图', time: '2021-03-02 15:47:44~2017-03-12 15:47:44', clicks: 444, status: '上线' },
  { name: '新品尝鲜', img: '', position: '首页轮播图', time: '2021-03-02 15:47:44~2017-03-12 15:47:44', clicks: 333, status: '上线' },
  { name: '积分兑换', img: '', position: '首页轮播图', time: '2021-03-02 15:47:44~2017-03-12 15:47:44', clicks: 222, status: '上线' },
];
const adList = ref([...allAds]);

// 分页相关
const pageSize = ref(5);
const currentPage = ref(1);
const pageSizes = [2, 5, 10]; // 保持可选项不变，默认显示5条

const pagedAds = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  return adList.value.slice(start, start + pageSize.value);
});

const handleSearch = () => {
  const keyword = searchForm.value.name.trim();
  if (!keyword) {
    adList.value = [...allAds];
    return;
  }
  adList.value = allAds.filter(ad => ad.name.includes(keyword));
};
const handleReset = () => {
  searchForm.value.name = '';
  adList.value = [...allAds];
};

const handlePageChange = (page: number) => {
  currentPage.value = page;
};

const showOfflineDialog = ref(false);
const offlineIndex = ref(-1);
const offlineName = ref('');

function handleOffline(index: number, row: any) {
  offlineIndex.value = index;
  offlineName.value = row.name;
  showOfflineDialog.value = true;
}
function confirmOffline() {
  if (offlineIndex.value > -1) {
    adList.value[offlineIndex.value].status = '下线';
    localStorage.setItem('adList', JSON.stringify(adList.value));
  }
  showOfflineDialog.value = false;
}

const showDeleteDialog = ref(false);
const deleteIndex = ref(-1);
const deleteName = ref('');

function handleDelete(index: number, row: any) {
  deleteIndex.value = index;
  deleteName.value = row.name;
  showDeleteDialog.value = true;
}
function confirmDelete() {
  if (deleteIndex.value > -1) {
    adList.value.splice(deleteIndex.value, 1);
    localStorage.setItem('adList', JSON.stringify(adList.value));
  }
  showDeleteDialog.value = false;
}

function handleRowClick(row: any) {
  if (typeof row.clicks === 'number') {
    row.clicks++;
    localStorage.setItem('adList', JSON.stringify(adList.value));
  }
}
</script>

<style scoped>
.ad-container {
  background: #fff;
  padding: 24px 18px 0 18px;
  min-height: 600px;
}
.ad-search-bar {
  margin-bottom: 10px;
}
.ad-img-placeholder {
  width: 48px;
  height: 48px;
  background: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  color: #bbb;
  font-size: 28px;
}
.ad-pagination {
  display: flex;
  align-items: center;
  margin-top: 10px;
}
.ad-total {
  margin-left: 18px;
  color: #888;
  font-size: 15px;
}
.el-pagination.is-background .el-pager li.is-active {
  background: #ff2d2d;
  color: #fff;
  border-radius: 4px;
}
.el-pagination.is-background .el-pager li {
  min-width: 32px;
  height: 32px;
  line-height: 32px;
  font-size: 18px;
}
.el-pagination.is-background .btn-prev, .el-pagination.is-background .btn-next, .el-pagination.is-background .el-pager li {
  border-radius: 4px;
}
.el-pagination.is-background .btn-prev.is-disabled, .el-pagination.is-background .btn-next.is-disabled {
  background: #f5f5f5;
  color: #bbb;
}
.el-pagination.is-background .el-select-dropdown__item.selected {
  color: #ff2d2d;
}
.ad-upload-box {
  width: 100px;
  height: 50px;
  border: 1px dashed #dcdfe6;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fafbfc;
  cursor: pointer;
}
.ad-upload-placeholder {
  font-size: 32px;
  color: #bbb;
}
</style>